package com.xxl.job.spring.starter;

import com.xxl.job.core.context.XxlJobHelper;
import com.xxl.job.core.handler.annotation.XxlJob;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.reflect.MethodSignature;

import java.io.StringReader;
import java.lang.annotation.Annotation;
import java.lang.reflect.Method;
import java.util.Properties;

@Aspect
public class XxlJobAspect {


    @Around(value = "@annotation(xxljob)")
    public Object doAround(ProceedingJoinPoint joinPoint, XxlJob xxljob) throws Throwable {
        long start = System.currentTimeMillis();

        MethodSignature signature = (MethodSignature) joinPoint.getSignature();
        Method method = signature.getMethod();
        String methodName = method.getDeclaringClass().getSimpleName() + "." + method.getName();
        String jobName = xxljob.value();
        WebConsoleLog.info(" <<<---  {} [{}] 任务开始  --->>> ", methodName, jobName);


        // 读取任务参数
        Properties jobParamProps = new Properties();
        String jobParam = XxlJobHelper.getJobParam();
        if (jobParam != null) {
            jobParamProps.load(new StringReader(jobParam));
        }
        Object[] methodArgs = joinPoint.getArgs();
        for (int i = 0; i < method.getParameterCount(); i++) {
            Annotation[] annotations = method.getParameterAnnotations()[i];
            for (Annotation annotation : annotations) {
                if (annotation instanceof JobParam) {
                    String paramName = ((JobParam) annotation).value();
                    methodArgs[i] = jobParamProps.getProperty(paramName);
                }
            }
        }
        Object result = joinPoint.proceed(methodArgs);
        long end = System.currentTimeMillis();
        WebConsoleLog.info(" <<<---  {} [{}] 任务结束，耗时 {}  --->>> ", methodName, jobName, end - start);
        return result;
    }
}
